package cn.wen233.srpc.core.server.handletask;

import cn.wen233.srpc.basic.model.Request;
import cn.wen233.srpc.basic.model.Response;
import cn.wen233.srpc.basic.serialize.Serializer;
import cn.wen233.srpc.basic.utils.IoUtils;
import cn.wen233.srpc.core.service.spi.SPIContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.Socket;

/**
 * 使用第三方序列化工具实现序列化
 *
 * @author wenei
 * @date 2021-10-29 15:33
 */
public class SerializeTask extends AbstractTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(SerializeTask.class);

    private static final Serializer serializer = SPIContext.loadSingleService(Serializer.class);

    private Socket clientSocket;

    public SerializeTask(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try {
            // 通过序列化器将inputStream的数据转化成Request对象
            Request request = serializer.deserialize(IoUtils.inputStreamToByteArray(clientSocket.getInputStream()), Request.class);
            // 调用服务端Executor处理Request
            Response response = SERVER_EXECUTOR.execute(request);
            // 返回Response给Client
            clientSocket.getOutputStream().write(serializer.serialize(response));
            LOGGER.info("{}:{} 请求执行{}.{}方法", clientSocket.getInetAddress(), clientSocket.getPort(), request.getServiceName(), request.getMethodName());
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
